package com.shopUser.service.impl;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shopFund.bean.UserFund;
import com.shopFund.feign.UserFundFeign;
import com.shopUser.Enum.Level;
import com.shopUser.bean.User;
import com.shopUser.dao.UserMapper;
import com.shopUser.service.IUserService;

import shopBean.common.utils.DateCommonUtils;
import shopBean.common.utils.RestResultGenerator;
import shopBean.common.utils.Tool;
import shopBean.common.utils.UUIDGenerator;
import shopBean.common.Exception.MyException;
import shopBean.common.bean.RestResult;
import shopBean.common.responseCode.Status;
@Service("userService")
public class UserServiceImpl implements IUserService {
	@Autowired
	UserMapper userMapper;
	@Autowired
	UserFundFeign userFundFeign;
	@Transactional
	public int insert(User user) {
		user.setId(UUIDGenerator.generate38());
		user.setCreateDate(DateCommonUtils.getCurrent());
		user.setPassword(Tool.md5Password(user.getPassword()));
		user.setLevel(Level.ordinary);
		int result = userMapper.insert(user);
		if(result <= 0) {
			throw new MyException(Status.init_user_error,"初始化用户失败");
		}
		UserFund userFund = new UserFund();
		userFund.setUserId(user.getId());
		userFund.setMoney(new BigDecimal(0.0));
		userFund.setScore(new BigDecimal(0.0));
		RestResult restResult = userFundFeign.insert(userFund );
		if(restResult== null || restResult.getData() == null ||Integer.valueOf(restResult.getData().toString()) <=0) {
			throw new MyException(Status.init_userFund_error,"初始化资金失败");
		}
		return 1;
	}

	public User get(String id) {
		// TODO Auto-generated method stub
		return userMapper.get(id);
	}
	@Transactional
	public int delete(String userId) {
		// TODO Auto-generated method stub
		return this.userMapper.delete(userId);
	}

	public User getByAccount(String account) {
		// TODO Auto-generated method stub
		return userMapper.getByAccount(account);
	}

	public RestResult<User> login(String account, String password) {
		User user = this.getByAccount(account) ;
		if(user == null) {
			return RestResultGenerator.genErrorResult("账号密码错误", null, Status.user_password_error);
		}
		if(!user.getPassword().equals(Tool.md5Password(password))) {
			return RestResultGenerator.genErrorResult("账号密码错误", null, Status.user_password_error);
		}
		return RestResultGenerator.genSuccessResult(user);
	}
}
